﻿using System;
using System.Net;
using ControleRepresentanteSync.ControleRepresentanteServices;
using ControleRepresentanteSync.Logic.Exceptions;

namespace ControleRepresentanteSync.Logic
{
    public interface ISyncServiceProvider
    {
        T Execute<T>(Func<SyncService, T> func);
        void Execute(Action<SyncService> action);
    }
    
    internal class SyncServiceProvider : ISyncServiceProvider
    {
        private readonly ConfigurationInfo m_ConfigurationInfo;

        public SyncServiceProvider(ConfigurationInfo configurationInfo)
        {
            m_ConfigurationInfo = configurationInfo;
        }

        public T Execute<T>(Func<SyncService, T> func)
        {
            SyncService syncService = new SyncService { CookieContainer = new CookieContainer() };
            try
            {
                if (!syncService.Login(m_ConfigurationInfo.Username, m_ConfigurationInfo.Password))
                {
                    throw new InvalidLoginException();
                }
                return func(syncService);
            }
            catch(WebException ex)
            {
                throw new ServerUnavailableException(ex);
            }
            finally
            {
                try
                {
                    syncService.Logout();
                }
                catch{}
            }
        }

        public void Execute(Action<SyncService> action)
        {
            Execute<object>(x =>
            {
                action(x);
                return null;
            });
        }
    }
}